package ru.housewife.service.wares;

import org.hibernate.Query;
import org.hibernate.Session;
import ru.common.hibernate.HibernateAction;
import ru.housewife.cache.CacheManager;
import ru.housewife.form.IngredientForm;
import ru.housewife.form.WareForm;
import ru.housewife.form.WaresGroupForm;
import ru.housewife.model.Ware;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class GetAllWares implements HibernateAction<List<WareForm>> {

    private CacheManager cacheManager;

    public GetAllWares(CacheManager cacheManager) {
        this.cacheManager = cacheManager;
    }

    @Override
    public List<WareForm> execute(Session session) {
        Query q = session.createQuery("select w from Ware w");

        List<Ware> lst = q.list();
        List<WareForm> result = new ArrayList<WareForm>(lst.size());
        for (Ware ware : lst) {
            WaresGroupForm group = cacheManager.getWaresGroupForm(ware.getWaresGroup().getId());
            IngredientForm ingredient = cacheManager.getIngredientForm(ware.getIngredient().getId());
            result.add(createWareForm(ware, group, ingredient));
        }
        return result;
    }

    private WareForm createWareForm(Ware ware, WaresGroupForm group, IngredientForm ingredient) {
        WareForm frm = new WareForm();
        frm.setId(ware.getId());
        frm.setName(ware.getName());
        frm.setMeasure(ware.getMeasure());
        frm.setCount(ware.getCount());
        frm.setIngredientsDefault(ware.isIngredientsDefault());

        frm.setGroupForm(group);
        group.addWare(frm);

        frm.setIngredient(ingredient);
        ingredient.addWare(frm);

        return frm;
    }
}
